package com.Tradition.controller.user;

import com.Tradition.common.check.StringCheckUtils;
import com.Tradition.common.http.HttpResult;
import com.Tradition.common.http.HttpResultEnum;
import com.Tradition.common.http.VerificationCodeEnum;
import com.Tradition.constant.SessionEnum;
import com.Tradition.controller.BaseController;
import com.Tradition.model.User;
import com.Tradition.service.UserLoginService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value="用户登陆",tags={"用户登录"})
@RestController
@RequestMapping("login")
public class LoginController extends BaseController {
    @Autowired
    UserLoginService userLoginService;
    @ApiOperation(value="用户登录接口",notes="用户用户登录")
    @PostMapping("login.do")
    public HttpResult login(@ApiParam(name="用户名",value="username",required=true) String username, @ApiParam(name="密码",value="password",required=true) String password, @ApiParam(name="验证码",value="code",required=true)String code, HttpSession session){
        logger.info("请求参数："+username+","+password+","+code);
        if(code==null||!session.getAttribute(VerificationCodeEnum.LOGIN.getName()).equals(code)){
            return HttpResult.newInstance(HttpResultEnum.VERIFICATIONCODE_ERROR);
        }
        if(!StringCheckUtils.UserNameFormat(username)){
            return HttpResult.newInstance(HttpResultEnum.USERNAME_FORMAT_ERROR);
        }
        if(!StringCheckUtils.PasswordFormat(password)){
            return HttpResult.newInstance(HttpResultEnum.PASSWORD_FORMAT_ERROR);
        }
        User user = userLoginService.QueryUser(username, password);
        session.setAttribute(SessionEnum.USER.getSessionKey(),user);
        return HttpResult.newInstance(HttpResultEnum.SUCCESS);
    }
}
